import { API_CONFIG } from '../config/apiConfig';

export const sendTextMessage = async (message, toUserName, statusCallback) => {
  // 立即返回，允许UI继续渲染
  const sendPromise = new Promise( (resolve, reject) => {
    try {
      // 如果提供了回调函数，通知消息发送中
      if (statusCallback) {
        statusCallback('sending');
      }
      
      // 使用AbortController实现请求超时控制
      const controller = new AbortController();
      const timeoutId = setTimeout(() => {
        controller.abort();
      }, 5000); // 5秒超时限制
      (async () => {
      try {
        const response = await fetch(`${API_CONFIG.HOST}/message/SendTextMessage?key=${API_CONFIG.KEY}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            MsgItem: [{
              AtWxIDList: [],
              ImageContent: "",
              MsgType: 0,
              TextContent: message,
              ToUserName: toUserName
            }]
          }),
          signal: controller.signal // 添加AbortController信号
        });

        // 清除超时定时器
        clearTimeout(timeoutId);

        if (!response.ok) {
          throw new Error('发送消息失败');
        }
        
        const result = await response.json();
        
        // 发送成功，通知UI更新状态
        if (statusCallback) {
          statusCallback('sent', result);
        }
        
        resolve(result);
      } catch (error) {
        // 清除超时定时器
        clearTimeout(timeoutId);
        
        // 判断是否是超时错误
        if (error.name === 'AbortError') {
          const timeoutError = new Error('请求超时，发送消息失败');
          console.error('发送消息超时:', timeoutError);
          
          if (statusCallback) {
            statusCallback('failed', timeoutError);
          }
          
          reject(timeoutError);
        } else {
          console.error('发送消息时出错:', error);
          
          if (statusCallback) {
            statusCallback('failed', error);
          }
          
          reject(error);
        }
      }
    })();
    } catch (outerError) {
      console.error('发送消息过程中发生错误:', outerError);
      
      if (statusCallback) {
        statusCallback('failed', outerError);
      }
      
      reject(outerError);
    }
  });
  
  // 返回Promise，但不等待它完成
  return sendPromise;
};


export const sendImageMessage = async (imageContent, toUserName, statusCallback) => {
  // 立即返回，允许UI继续渲染
  const sendPromise = new Promise( (resolve, reject) => {
    try {
      // 如果提供了回调函数，通知消息发送中
      if (statusCallback) {
        statusCallback('sending');
      }
      
      // 使用AbortController实现请求超时控制
      const controller = new AbortController();
      const timeoutId = setTimeout(() => {
        controller.abort();
      }, 5000); // 5秒超时限制
      (async () => {
      try {
        const response = await fetch(`${API_CONFIG.HOST}/message/SendImageMessage?key=${API_CONFIG.KEY}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            MsgItem: [{
              AtWxIDList: [],
              ImageContent: imageContent,
              MsgType: 3, // 3表示图片消息
              TextContent: "",
              ToUserName: toUserName
            }]
          }),
          signal: controller.signal // 添加AbortController信号
        });

        // 清除超时定时器
        clearTimeout(timeoutId);

        if (!response.ok) {
          throw new Error('发送图片消息失败');
        }
        
        const result = await response.json();
        
        // 发送成功，通知UI更新状态
        if (statusCallback) {
          statusCallback('sent', result);
        }
        
        resolve(result);
      } catch (error) {
        // 清除超时定时器
        clearTimeout(timeoutId);
        
        // 判断是否是超时错误
        if (error.name === 'AbortError') {
          const timeoutError = new Error('请求超时，发送图片消息失败');
          console.error('发送图片消息超时:', timeoutError);
          
          if (statusCallback) {
            statusCallback('failed', timeoutError);
          }
          
          reject(timeoutError);
        } else {
          console.error('发送图片消息时出错:', error);
          
          if (statusCallback) {
            statusCallback('failed', error);
          }
          
          reject(error);
        }
      }
    })();
    } catch (outerError) {
      console.error('发送图片消息过程中发生错误:', outerError);
      
      if (statusCallback) {
        statusCallback('failed', outerError);
      }
      
      reject(outerError);
    }
  });
  
  // 返回Promise，但不等待它完成
  return sendPromise;
};

export const getChatRoomInfo = async (chatRoomIds) => {
  try {
    const response = await fetch(`${API_CONFIG.HOST}/group/GetChatRoomInfo?key=${API_CONFIG.KEY}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        ChatRoomWxIdList: chatRoomIds
      })
    });

    if (!response.ok) {
      throw new Error('获取群聊信息失败');
    }
    
    const data = await response.json();
    if (data.Code === 200) {
      return data.Data;
    }
    throw new Error('获取群聊信息失败');
  } catch (error) {
    console.error('获取群聊信息失败:', error);
    throw error;
  }
};

export const getContactDetailsList = async (RoomWxIDList = [], UserNames = []) => {
  try {
    const response = await fetch(`${API_CONFIG.HOST}/friend/GetContactDetailsList?key=${API_CONFIG.KEY}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        RoomWxIDList,
        UserNames
      })
    });
    console.log(JSON.stringify({
        RoomWxIDList,
        UserNames
      }));
    if (!response.ok) {
      throw new Error('获取联系人详情失败');
    }
    
    const data = await response.json();
    console.log(data);
    if (data.Code === 200) {
      if (!data.Data.contactList || data.Data.contactList.length === 0) {
        throw new Error('联系人列表为空');
      }
      const contact = data.Data.contactList[0];
      return {
        id: contact.userName.str,
        name: contact.nickName.str,
        avatar: contact.smallHeadImgUrl
      };
    }
    throw new Error('获取联系人详情失败');
  } catch (error) {
    console.error('获取联系人详情失败:', error);
    throw error;
  }
};

export const getLoginQrCode = async () => {
  try {
    const response = await fetch(`${API_CONFIG.HOST}/login/GetLoginQrCodeNewX?key=${API_CONFIG.KEY}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        Check: false,
        Proxy: ""
      })
    });

    if (!response.ok) {
      throw new Error('获取二维码失败');
    }
    
    const data = await response.json();
    if (data.Code === 200) {
      return data.Data.QrCodeUrl;
    }else if(data.Code === -3){
      if(data.Text && data.Text.includes('已绑定')){
        return 1;
      }
    }
    throw new Error('获取二维码失败');
  } catch (error) {
    console.error('获取二维码失败:', error);
    throw error;
  }
};

export const getInitStatus = async () => {
  try {
    const response = await fetch(`${API_CONFIG.HOST}/login/GetInItStatus?key=${API_CONFIG.KEY}`);
    const data = await response.json();
    if (data.Code === 200) {
      return data.Data;
    }
    throw new Error(data.Text || '检查初始化状态失败');
  } catch (error) {
    console.error('检查初始化状态失败:', error);
    throw error;
  }
};
export const getLoginStatus = async () => {
  try {
    const response = await fetch(`${API_CONFIG.HOST}/login/GetLoginStatus?key=${API_CONFIG.KEY}`);
    const data = await response.json();
    if (data.Code === 200) {

      return data.Data.loginState===1;
    }else if(data.Code === 300){
      return false;
    }
    throw new Error(data.Text || '检查初始化状态失败');
  } catch (error) {
    console.error('检查初始化状态失败:', error);
    throw error;
  }
};


export const getUserProfile = async () => {
  try {
    const response = await fetch(`${API_CONFIG.HOST}/user/GetProfile?key=${API_CONFIG.KEY}`);
    const data = await response.json();
    if (data.Code === 200) {
      return {
        id: data.Data.userInfo.userName.str,
        name: data.Data.userInfo.nickName.str,
        avatar: data.Data.userInfoExt.smallHeadImgUrl,
        wxid: data.Data.userInfo.userName.str,
      };
    }
    throw new Error('获取用户信息失败');
  } catch (error) {
    console.error('获取用户信息失败:', error);
    throw error;
  }
};